extends Node
class_name GameManager

# 预加载类
const Enemy = preload("res://scripts/character/enemy.gd")

# 游戏状态枚举
enum GameState {
	MAIN_MENU,    # 主菜单
	GAME_RUNNING, # 游戏运行中
	BATTLE,       # 战斗中
	DIALOGUE,     # 对话中
	INVENTORY,    # 背包界面
	SKILLS,       # 技能界面
	CULTIVATION,  # 修炼界面
	PAUSED,       # 游戏暂停
	CHARACTER_CREATION # 角色创建
}

# 当前游戏状态
var current_state: int = GameState.MAIN_MENU

# 游戏系统引用
var player: Player
var battle_system: BattleSystem
var story_system: StorySystem

# UI引用
@onready var ui_layer = $"../UI"
@onready var main_menu = $"../UI/MainMenu"
@onready var game_ui = $"../UI/GameUI"
@onready var battle_ui = $"../UI/BattleUI"
@onready var creater_player_ui = $"../UI/CharacterCreation"
@onready var save_slots_ui = $"../UI/SaveSlotsUI"
@onready var cultivation_ui = $"../UI/CultivationUI"
@onready var equipment_ui = $"../UI/EquipmentUI"
@onready var skills_ui = $"../UI/SkillsUI"

# 游戏数据
var game_data: Dictionary = {}
var save_slots: Array[String] = [
	"user://save_data_1.json",
	"user://save_data_2.json",
	"user://save_data_3.json",
	"user://save_data_4.json",
	"user://save_data_5.json"
]
var current_slot: int = 0 # 当前选择的存档槽位
var save_info: Dictionary = {} # 存储每个存档的预览信息

# 信号
signal game_state_changed(new_state)
signal game_saved()
signal game_loaded()

# 延迟初始化完成回调
func _on_initialization_delay_completed() -> void:
		# 初始化游戏系统
	_initialize_systems()
	
	change_game_state(GameState.MAIN_MENU)

# 初始化游戏
func _ready() -> void:
	# 连接UI按钮信号
	_connect_ui_signals()
	
	# 添加初始化延迟计时器
	var init_timer = Timer.new()
	init_timer.wait_time = 1.0
	init_timer.one_shot = true
	init_timer.autostart = true
	init_timer.timeout.connect(_on_initialization_delay_completed)
	add_child(init_timer)
	
	# 设置初始状态
	# change_game_state(GameState.MAIN_MENU) 现在由计时器触发

# 连接UI按钮信号
func _connect_ui_signals() -> void:
	# 主菜单按钮
	var start_button = main_menu.get_node("VBoxContainer/StartButton")
	var load_button = main_menu.get_node("VBoxContainer/LoadButton")
	var settings_button = main_menu.get_node("VBoxContainer/SettingsButton")
	var quit_button = main_menu.get_node("VBoxContainer/QuitButton")
	
	start_button.pressed.connect(_on_start_button_pressed)
	load_button.pressed.connect(_on_load_button_pressed)
	settings_button.pressed.connect(_on_settings_button_pressed)
	quit_button.pressed.connect(_on_quit_button_pressed)
	
	# 游戏UI按钮
	var cultivate_button = game_ui.get_node("ActionButtons/CultivateButton")
	var explore_button = game_ui.get_node("ActionButtons/ExploreButton")
	var inventory_button = game_ui.get_node("ActionButtons/InventoryButton")
	var skills_button = game_ui.get_node("ActionButtons/SkillsButton")
	var save_button = game_ui.get_node("ActionButtons/SaveButton")
	
	cultivate_button.pressed.connect(_on_cultivate_button_pressed)
	explore_button.pressed.connect(_on_explore_button_pressed)
	inventory_button.pressed.connect(_on_inventory_button_pressed)
	skills_button.pressed.connect(_on_skills_button_pressed)
	save_button.pressed.connect(_on_save_button_pressed)
	
	# 战斗UI按钮
	var attack_button = battle_ui.get_node("ActionButtons/AttackButton")
	var skill_button = battle_ui.get_node("ActionButtons/SkillButton")
	var item_button = battle_ui.get_node("ActionButtons/ItemButton")
	var flee_button = battle_ui.get_node("ActionButtons/FleeButton")
	
	attack_button.pressed.connect(_on_attack_button_pressed)
	skill_button.pressed.connect(_on_skill_button_pressed)
	item_button.pressed.connect(_on_item_button_pressed)
	flee_button.pressed.connect(_on_flee_button_pressed)

# 初始化游戏系统
func _initialize_systems() -> void:
	# 创建玩家
	player = Player.new()
	
	# 创建战斗系统
	battle_system = BattleSystem.new()
	add_child(battle_system)
	
	# 创建剧情系统
	story_system = StorySystem.new()
	add_child(story_system)
	
	# 连接系统信号
	battle_system.battle_ended.connect(_on_battle_ended)
	story_system.quest_started.connect(_on_quest_started)
	story_system.quest_completed.connect(_on_quest_completed)
	story_system.random_event_triggered.connect(_on_random_event_triggered)
	story_system.dialogue_started.connect(_on_dialogue_started)
	
	# 初始化UI界面
	_initialize_ui_systems()

# 初始化UI系统
func _initialize_ui_systems() -> void:
	# 获取数据管理器
	var data_manager = get_node("/root/MainScene/DataManager")
	
	# 创建修炼系统
	var cultivation_system = CultivationSystem.new()
	add_child(cultivation_system)
	
	# 初始化UI界面（但不显示）
	if cultivation_ui:
		cultivation_ui.initialize(player, data_manager, cultivation_system)
		var close_button = cultivation_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
		if not close_button.is_connected("pressed", _on_cultivation_ui_close_pressed):
			close_button.pressed.connect(_on_cultivation_ui_close_pressed)
	
	if equipment_ui:
		equipment_ui.initialize(player, data_manager)
		var close_button = equipment_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
		if not close_button.is_connected("pressed", _on_equipment_ui_close_pressed):
			close_button.pressed.connect(_on_equipment_ui_close_pressed)
	
	if skills_ui:
		skills_ui.initialize(player, data_manager)
		var close_button = skills_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
		if not close_button.is_connected("pressed", _on_skills_ui_close_pressed):
			close_button.pressed.connect(_on_skills_ui_close_pressed)

# UI界面关闭按钮回调函数
func _on_cultivation_ui_close_pressed() -> void:
	# 隐藏修炼界面
	cultivation_ui.hide_ui()
	
	# 返回游戏状态
	change_game_state(GameState.GAME_RUNNING)

# 装备界面关闭按钮回调函数
func _on_equipment_ui_close_pressed() -> void:
	# 隐藏装备界面
	equipment_ui.hide_ui()
	
	# 返回游戏状态
	change_game_state(GameState.GAME_RUNNING)

# 技能界面关闭按钮回调函数
func _on_skills_ui_close_pressed() -> void:
	# 隐藏技能界面
	skills_ui.hide_ui()
	
	# 返回游戏状态
	change_game_state(GameState.GAME_RUNNING)

# 战斗中技能界面关闭按钮回调函数
func _on_battle_skills_ui_close_pressed() -> void:
	# 隐藏技能界面
	skills_ui.hide_ui()
	
	# 恢复战斗系统
	battle_system.set_paused(false)
	
	# 更新战斗UI
	_update_battle_ui()

# 战斗中装备界面关闭按钮回调函数
func _on_battle_equipment_ui_close_pressed() -> void:
	# 隐藏装备界面
	equipment_ui.hide_ui()
	
	# 恢复战斗系统
	battle_system.set_paused(false)
	
	# 更新战斗UI
	_update_battle_ui()

# 改变游戏状态
func change_game_state(new_state: int) -> void:
	var old_state = current_state
	current_state = new_state
	
	# 根据状态显示/隐藏UI
	match new_state:
		GameState.MAIN_MENU:
			main_menu.visible = true
			game_ui.visible = false
			battle_ui.visible = false
			creater_player_ui.visible = false
			save_slots_ui.visible = false
			cultivation_ui.visible = false
			equipment_ui.visible = false
			skills_ui.visible = false
		
		GameState.CHARACTER_CREATION:
			main_menu.visible = false
			game_ui.visible = false
			battle_ui.visible = false
			creater_player_ui.visible = true
			save_slots_ui.visible = false
			cultivation_ui.visible = false
			equipment_ui.visible = false
			skills_ui.visible = false
		
		GameState.GAME_RUNNING:
			main_menu.visible = false
			game_ui.visible = true
			battle_ui.visible = false
			creater_player_ui.visible = false
			save_slots_ui.visible = false
			cultivation_ui.visible = false
			equipment_ui.visible = false
			skills_ui.visible = false
			
			# 更新游戏UI
			_update_game_ui()
		
		GameState.BATTLE:
			main_menu.visible = false
			game_ui.visible = false
			battle_ui.visible = true
			creater_player_ui.visible = false
			save_slots_ui.visible = false
			cultivation_ui.visible = false
			equipment_ui.visible = false
			skills_ui.visible = false
			
			# 更新战斗UI
			_update_battle_ui()
		
		GameState.DIALOGUE:
			# 对话状态下保持游戏UI可见
			main_menu.visible = false
			game_ui.visible = true
			battle_ui.visible = false
			creater_player_ui.visible = false
			save_slots_ui.visible = false
			cultivation_ui.visible = false
			equipment_ui.visible = false
			skills_ui.visible = false
		
		GameState.CULTIVATION:
			main_menu.visible = false
			game_ui.visible = false
			battle_ui.visible = false
			creater_player_ui.visible = false
			save_slots_ui.visible = false
			cultivation_ui.visible = true
			equipment_ui.visible = false
			skills_ui.visible = false
		
		GameState.INVENTORY:
			main_menu.visible = false
			game_ui.visible = false
			battle_ui.visible = false
			creater_player_ui.visible = false
			save_slots_ui.visible = false
			cultivation_ui.visible = false
			equipment_ui.visible = true
			skills_ui.visible = false
		
		GameState.SKILLS:
			main_menu.visible = false
			game_ui.visible = false
			battle_ui.visible = false
			creater_player_ui.visible = false
			save_slots_ui.visible = false
			cultivation_ui.visible = false
			equipment_ui.visible = false
			skills_ui.visible = true
	
	# 发出状态改变信号
	emit_signal("game_state_changed", new_state)

# 更新游戏UI
func _update_game_ui() -> void:
	if not player:
		return
	
	# 更新玩家信息
	var name_label = game_ui.get_node("PlayerInfo/NameLabel")
	var realm_label = game_ui.get_node("PlayerInfo/RealmLabel")
	var health_bar = game_ui.get_node("PlayerInfo/HealthBar")
	
	name_label.text = "姓名: " + player.name
	realm_label.text = "境界: " + player.get_realm_name()
	health_bar.max_value = player.max_health
	health_bar.value = player.current_health

# 更新战斗UI
func _update_battle_ui() -> void:
	if not player or not battle_system:
		return
	
	# 更新玩家信息
	var player_name = battle_ui.get_node("PlayerPanel/NameLabel")
	var player_health = battle_ui.get_node("PlayerPanel/HealthBar")
	var player_spirit = battle_ui.get_node("PlayerPanel/SpiritBar")
	
	player_name.text = player.name
	player_health.max_value = player.max_health
	player_health.value = player.current_health
	player_spirit.max_value = player.max_spirit
	player_spirit.value = player.current_spirit
	
	# 更新敌人信息（如果有）
	if battle_system.enemies.size() > 0:
		var enemy = battle_system.enemies[0]
		var enemy_name = battle_ui.get_node("EnemyPanel/NameLabel")
		var enemy_health = battle_ui.get_node("EnemyPanel/HealthBar")
		
		enemy_name.text = enemy.name
		enemy_health.max_value = enemy.max_health
		enemy_health.value = enemy.current_health
	
	# 更新战斗日志
	var battle_log = battle_ui.get_node("BattleLog")
	battle_log.text = ""
	
	for log_entry in battle_system.battle_log:
		battle_log.text += log_entry + "\n"

# 开始新游戏
func start_new_game() -> void:
	# 切换到角色创建状态
	change_game_state(GameState.CHARACTER_CREATION)
	
	# 获取角色创建界面引用
	var character_creation = $"../UI/CharacterCreation"
	
	# 断开之前可能存在的连接，避免重复连接
	if character_creation.is_connected("character_created", _on_character_created):
		character_creation.disconnect("character_created", _on_character_created)
	
	if character_creation.is_connected("creation_cancelled", _on_character_creation_cancelled):
		character_creation.disconnect("creation_cancelled", _on_character_creation_cancelled)
	
	# 连接角色创建信号
	character_creation.character_created.connect(_on_character_created)
	character_creation.creation_cancelled.connect(_on_character_creation_cancelled)

# 处理角色创建完成的回调
func _on_character_created(character_name: String) -> void:
	# 验证名称
	if character_name.length() == 0:
		return
	
	# 创建新玩家
	player = Player.new(character_name)
	
	# 初始化剧情
	_initialize_story()
	
	# 切换到游戏状态
	change_game_state(GameState.GAME_RUNNING)

# 保存游戏
func save_game(slot: int = -1) -> void:
	# 如果没有指定槽位，使用当前槽位
	if slot >= 0:
		current_slot = slot
	
	# 准备保存数据
	game_data = {
		"save_info": {
			"timestamp": Time.get_datetime_string_from_system(),
			"player_name": player.player_name,
			"level": player.level,
			"realm": player.get_realm_name()
		},
		"player": {
			"name": player.player_name,
			"level": player.level,
			"experience": player.experience,
			"cultivation_realm": player.cultivation_realm,
			"spirit_roots": player.spirit_roots,
			"spirit_root_quality": player.spirit_root_quality,
			"max_health": player.max_health,
			"current_health": player.current_health,
			"max_spirit": player.max_spirit,
			"current_spirit": player.current_spirit,
			"attack": player.attack,
			"defense": player.defense,
			"speed": player.speed,
			"spirit_stones": player.spirit_stones,
			# 背包数据
			"inventory": player.inventory.map(func(item): return {
				"item_name": item.item_name,
				"description": item.description,
				"item_type": item.item_type,
				"health_restore": item.health_restore,
				"spirit_restore": item.spirit_restore,
				"stack_size": item.stack_size,
				"max_stack": item.max_stack,
				"quality": item.quality,
				"value": item.value,
				"can_equip": item.can_equip,
				"equip_slot": item.equip_slot if item.can_equip else -1,
				"health_bonus": item.health_bonus if item.can_equip else 0,
				"spirit_bonus": item.spirit_bonus if item.can_equip else 0,
				"attack_bonus": item.attack_bonus if item.can_equip else 0,
				"defense_bonus": item.defense_bonus if item.can_equip else 0,
				"speed_bonus": item.speed_bonus if item.can_equip else 0
			}),
			# 装备数据
			"equipment": {},
			# 功法数据
			"cultivation_technique": null
		},
		"story": {
			"current_chapter": story_system.current_chapter,
			"current_quest": story_system.current_quest,
			"completed_quests": story_system.completed_quests
		}
	}
	
	# 保存装备数据
	for equip_slot in player.equipment:
		var item = player.equipment[equip_slot]
		if item != null:
			game_data.player.equipment[str(equip_slot)] = {
				"item_name": item.item_name,
				"description": item.description,
				"item_type": item.item_type,
				"quality": item.quality,
				"value": item.value,
				"can_equip": item.can_equip,
				"equip_slot": item.equip_slot,
				"health_bonus": item.health_bonus,
				"spirit_bonus": item.spirit_bonus,
				"attack_bonus": item.attack_bonus,
				"defense_bonus": item.defense_bonus,
				"speed_bonus": item.speed_bonus
			}
	
	# 保存功法数据
	if player.cultivation_technique != null:
		var technique = player.cultivation_technique
		game_data.player.cultivation_technique = {
			"technique_name": technique.technique_name,
			"description": technique.description,
			"technique_type": technique.technique_type,
			"cultivation_speed_bonus": technique.cultivation_speed_bonus,
			"spirit_recovery_bonus": technique.spirit_recovery_bonus,
			"breakthrough_bonus": technique.breakthrough_bonus,
			"level": technique.level,
			"max_level": technique.max_level,
			"element_affinity": technique.element_affinity,
			"required_realm": technique.required_realm,
			"required_spirit_root": technique.required_spirit_root,
			"attack_bonus": technique.attack_bonus,
			"defense_bonus": technique.defense_bonus,
			"speed_bonus": technique.speed_bonus
		}
	
	# 优化JSON格式（新增缩进参数）
	var file = FileAccess.open(save_slots[current_slot], FileAccess.WRITE)
	if file:
		file.store_string(JSON.stringify(game_data, "\t"))
		file.close()
		
		# 更新存档预览信息
		save_info[current_slot] = game_data.save_info
		
		# 显示保存成功消息
		var story_text = game_ui.get_node("MainContent/StoryText")
		story_text.text += "\n\n[游戏已保存到存档槽位 %d]" % (current_slot + 1)
		
		emit_signal("game_saved")

# 加载游戏
func load_game(slot: int = -1) -> void:
	# 如果指定了槽位，更新当前槽位
	if slot >= 0:
		current_slot = slot
	
	# 隐藏所有UI界面
	main_menu.visible = false
	game_ui.visible = false
	battle_ui.visible = false
	creater_player_ui.visible = false
	save_slots_ui.visible = false
	
	# 检查存档文件是否存在
	var file = FileAccess.open(save_slots[current_slot], FileAccess.READ)
	if not file:
		# 如果存档不存在，返回主菜单
		change_game_state(GameState.MAIN_MENU)
		# 显示提示信息
		OS.alert("存档槽位 %d 没有存档数据！" % (current_slot + 1), "提示")
		return
	
	# 读取存档数据
	var json_string = file.get_as_text()
	file.close()
	
	# 解析JSON
	var json = JSON.new()
	var error = json.parse(json_string)
	if error == OK:
		game_data = json.data
		
		# 更新存档预览信息
		if game_data.has("save_info"):
			save_info[current_slot] = game_data.save_info
		
		# 恢复玩家数据
		player = Player.new(game_data.player.name)
		player.level = game_data.player.level
		player.experience = game_data.player.experience
		player.cultivation_realm = game_data.player.cultivation_realm
		player.spirit_roots = game_data.player.spirit_roots
		player.spirit_root_quality = game_data.player.spirit_root_quality
		player.max_health = game_data.player.max_health
		player.current_health = game_data.player.current_health
		player.max_spirit = game_data.player.max_spirit
		player.current_spirit = game_data.player.current_spirit
		player.attack = game_data.player.attack
		player.defense = game_data.player.defense
		player.speed = game_data.player.speed
		player.spirit_stones = game_data.player.spirit_stones
		
		# 加载背包数据
		player.inventory = []
		for item_data in game_data.player.get("inventory", []):
			var item = Item.new()
			item.item_name = item_data.item_name
			item.description = item_data.description
			item.item_type = item_data.item_type
			item.health_restore = item_data.get("health_restore", 0)
			item.spirit_restore = item_data.get("spirit_restore", 0)
			item.stack_size = item_data.get("stack_size", 1)
			item.max_stack = item_data.get("max_stack", 1)
			item.quality = item_data.get("quality", 0)
			item.value = item_data.get("value", 1)
			
			# 装备属性
			if item_data.get("can_equip", false):
				item.can_equip = true
				item.equip_slot = item_data.get("equip_slot", -1)
				item.health_bonus = item_data.get("health_bonus", 0)
				item.spirit_bonus = item_data.get("spirit_bonus", 0)
				item.attack_bonus = item_data.get("attack_bonus", 0)
				item.defense_bonus = item_data.get("defense_bonus", 0)
				item.speed_bonus = item_data.get("speed_bonus", 0)
			
			# 直接添加到背包数组，绕过堆叠逻辑
			player.inventory.append(item)
		
		# 发送背包更新信号
		player.emit_signal("inventory_changed")

		# 加载装备数据
		player.equipment = {}
		if game_data.player.has("equipment"):
			for slot_str in game_data.player.equipment:
				var equipment_slot = int(slot_str)
				var equip_data = game_data.player.equipment[slot_str]
				
				var equip_item = Item.new()
				equip_item.item_name = equip_data.item_name
				equip_item.description = equip_data.description
				equip_item.item_type = equip_data.item_type
				equip_item.quality = equip_data.quality
				equip_item.value = equip_data.value
				equip_item.can_equip = true
				equip_item.equip_slot = equip_data.equip_slot
				equip_item.health_bonus = equip_data.health_bonus
				equip_item.spirit_bonus = equip_data.spirit_bonus
				equip_item.attack_bonus = equip_data.attack_bonus
				equip_item.defense_bonus = equip_data.defense_bonus
				equip_item.speed_bonus = equip_data.speed_bonus
				
				player.equipment[equipment_slot] = equip_item
		
		# 加载功法数据
		if game_data.player.has("cultivation_technique") and game_data.player.cultivation_technique != null:
			var tech_data = game_data.player.cultivation_technique
			var technique = CultivationTechnique.new()
			
			technique.technique_name = tech_data.technique_name
			technique.description = tech_data.description
			technique.technique_type = tech_data.technique_type
			technique.cultivation_speed_bonus = tech_data.cultivation_speed_bonus
			technique.spirit_recovery_bonus = tech_data.spirit_recovery_bonus
			technique.breakthrough_bonus = tech_data.breakthrough_bonus
			technique.level = tech_data.level
			technique.max_level = tech_data.max_level
			technique.element_affinity = tech_data.element_affinity
			technique.required_realm = tech_data.required_realm
			technique.required_spirit_root = tech_data.required_spirit_root
			technique.attack_bonus = tech_data.attack_bonus
			technique.defense_bonus = tech_data.defense_bonus
			technique.speed_bonus = tech_data.speed_bonus
			
			player.cultivation_technique = technique



		# 恢复剧情数据
		story_system.current_chapter = game_data.story.current_chapter
		story_system.current_quest = game_data.story.current_quest
		story_system.completed_quests = game_data.story.completed_quests
		
		# 切换到游戏状态
		change_game_state(GameState.GAME_RUNNING)
		
		# 显示加载成功消息
		var story_text = game_ui.get_node("MainContent/StoryText")
		story_text.text = "从存档槽位 %d 加载游戏成功！\n\n你现在位于修仙世界，境界为%s。" % [current_slot + 1, player.get_realm_name()]
		
		emit_signal("game_loaded")

# 开始战斗
func start_battle(enemies: Array) -> void:
	# 初始化战斗系统
	battle_system.initialize_battle(player, enemies)
	
	# 切换到战斗状态
	change_game_state(GameState.BATTLE)

# 更新剧情选项
func _update_story_choices(choices: Array) -> void:
	var choices_container = game_ui.get_node("MainContent/ChoicesContainer")
	
	# 清除现有选项
	for child in choices_container.get_children():
		child.queue_free()
	
	# 添加新选项
	for i in range(choices.size()):
		var choice = choices[i]
		var button = Button.new()
		if choice is String:
			button.text = choice
		else:
			button.text = choice["text"]
		button.pressed.connect(_on_story_choice_pressed.bind(i))
		choices_container.add_child(button)

# 获取存档预览信息
func get_save_preview(slot: int) -> Dictionary:
	# 检查存档文件是否存在
	var file = FileAccess.open(save_slots[slot], FileAccess.READ)
	if not file:
		return {}
	
	# 读取存档数据
	var json_string = file.get_as_text()
	file.close()
	
	# 解析JSON
	var json = JSON.new()
	var error = json.parse(json_string)
	if error == OK and json.data.has("save_info"):
		return json.data.save_info
	return {}

# 更新所有存档预览信息
func update_save_previews() -> void:
	for i in range(save_slots.size()):
		var preview = get_save_preview(i)
		if not preview.is_empty():
			save_info[i] = preview

# 显示存档选择界面
func show_save_slots(is_save: bool) -> void:
	# 隐藏所有UI界面
	main_menu.visible = false
	game_ui.visible = false
	battle_ui.visible = false
	creater_player_ui.visible = false
	
	# 确保SaveSlotsUI可见
	save_slots_ui.visible = true
	
	# 初始化存档界面
	save_slots_ui.initialize(self)
	
	# 设置界面模式（保存/加载）
	save_slots_ui.set_mode(is_save)

# 按钮回调函数
func _on_start_button_pressed() -> void:
	start_new_game()

func _on_load_button_pressed() -> void:
	# 切换到游戏运行状态以显示游戏UI
	change_game_state(GameState.GAME_RUNNING)
	# 显示存档选择界面
	show_save_slots(false)

func _on_save_button_pressed() -> void:
	show_save_slots(true)

func _on_settings_button_pressed() -> void:
	# 设置功能待实现
	pass

func _on_quit_button_pressed() -> void:
	get_tree().quit()


func _on_cultivate_button_pressed() -> void:
	# 进入修炼状态
	change_game_state(GameState.CULTIVATION)
	
	# 初始化并显示修炼界面
	if not cultivation_ui.visible:
		# 获取数据管理器
		var data_manager = get_node("/root/MainScene/DataManager")
		
		# 获取修炼系统（如果没有则创建）
		var cultivation_system = get_node_or_null("CultivationSystem")
		if not cultivation_system:
			cultivation_system = CultivationSystem.new()
			add_child(cultivation_system)
		
		# 初始化修炼界面
		cultivation_ui.initialize(player, data_manager, cultivation_system)
		
		# 连接关闭按钮信号
		var close_button = cultivation_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
		if not close_button.is_connected("pressed", _on_cultivation_ui_close_pressed):
			close_button.pressed.connect(_on_cultivation_ui_close_pressed)
	
	# 显示修炼界面
	cultivation_ui.show_ui()


func _on_explore_button_pressed() -> void:
	# 生成随机数判断是否触发战斗（30%概率）
	var rand = randf()
	if rand < 0.3:
		# 获取数据管理器
		var data_manager = get_node("/root/MainScene/DataManager")
		
		# 筛选符合等级范围和位置的敌人
		var suitable_enemies = []
		for enemy_id in data_manager.enemies_data:
			var enemy_data = data_manager.enemies_data[enemy_id]
			if enemy_data.min_level <= player.level and enemy_data.max_level >= player.level:
				# TODO: 后续添加位置判断
				suitable_enemies.append(enemy_id)
		
		# 如果没有合适的敌人，返回
		if suitable_enemies.is_empty():
			return
		
		# 从合适的敌人中随机选择一个
		var random_enemy_id = suitable_enemies[randi() % suitable_enemies.size()]
		
		# 创建敌人实例
		var enemy = data_manager.create_enemy(random_enemy_id)
		
		# 初始化战斗系统
		battle_system.initialize_battle(player,[enemy])
		
		# 切换到战斗状态
		change_game_state(GameState.BATTLE)
		return
	
	# 获取故事文本控件
	var story_text = game_ui.get_node("MainContent/StoryText")	
	# 尝试获取随机事件
	var random_event = story_system.get_random_event()
	
	if not random_event.is_empty() and rand > 0.6 and rand < 0.9:
		# 触发随机事件
		story_text.text = "随机事件: %s\n\n%s" % [random_event.title, random_event.description]
		
		# 更新选项
		_update_story_choices(random_event.choices)
		
		# 发出随机事件触发信号
		story_system.emit_signal("random_event_triggered", random_event.id, random_event)
	elif rand < 0.6:
			# 获取数据管理器
		var data_manager = get_node("/root/MainScene/DataManager")
		
		# 筛选符合等级范围的物品
		var suitable_items = []
		for item_id in data_manager.items_data:
			var item_data = data_manager.items_data[item_id]
			if item_data.min_level <= player.level :
				suitable_items.append(item_id)
		
		# 如果没有合适的物品，返回
		if suitable_items.is_empty():
			return
		
		# 从合适的物品中随机选择一个
		var random_item_id = suitable_items[randi() % suitable_items.size()]
		
		# 创建物品实例
		var item = data_manager.create_item(random_item_id)
		
		# 添加到背包
		player.add_item(item)
		
		# 显示获得物品的信息
		story_text.text = "你在探索过程中发现了 %s！\n\n%s" % [item.item_name, item.description]
		
		# 更新UI
		_update_game_ui()
	elif rand < 1.0:
		# 40%几率触发随机事件
		story_text.text = "你在探索过程中遇到了一位老者，他似乎有话要对你说..."
			
			# 添加对话选项
		_update_story_choices(["上前询问", "谨慎观察", "绕道而行"])
	else:
		
		if rand < 0.3:
			# 30%几率遇到敌人，随机选择一种魔物
			var enemy_types = [
				{"name": "暗影魔蛛", "health_mod": 0.9, "spirit_mod": 1.2, "attack_mod": 1.3, "defense_mod": 0.8, "speed_mod": 1.4, "behavior": Enemy.AIBehavior.STRATEGIC},
				{"name": "赤焰魔狼", "health_mod": 1.1, "spirit_mod": 1.0, "attack_mod": 1.5, "defense_mod": 0.7, "speed_mod": 1.3, "behavior": Enemy.AIBehavior.AGGRESSIVE},
				{"name": "幽冥魔蝠", "health_mod": 0.7, "spirit_mod": 1.4, "attack_mod": 1.2, "defense_mod": 0.6, "speed_mod": 1.6, "behavior": Enemy.AIBehavior.RANDOM},
				{"name": "岩甲魔犀", "health_mod": 1.5, "spirit_mod": 0.8, "attack_mod": 0.9, "defense_mod": 1.8, "speed_mod": 0.7, "behavior": Enemy.AIBehavior.DEFENSIVE},
				{"name": "雷霆魔蜥", "health_mod": 1.2, "spirit_mod": 1.3, "attack_mod": 1.4, "defense_mod": 1.0, "speed_mod": 1.1, "behavior": Enemy.AIBehavior.SUPPORT}
			]
			
			# 随机选择一种魔物
			var enemy_type = enemy_types[randi() % enemy_types.size()]
			
			# 随机生成魔物等级（玩家等级-2到+2之间）
			var level_range_min = max(1, player.level - 2) # 确保等级不低于1
			var level_range_max = player.level + 2
			var enemy_level = randi_range(level_range_min, level_range_max)
			
			# 创建敌人实例
			var enemy = Enemy.new(enemy_type.name, enemy_level)
			enemy.enemy_type = Enemy.EnemyType.DEMON
			
			# 根据魔物类型调整属性
			enemy.max_health = int(enemy.max_health * enemy_type.health_mod)
			enemy.current_health = enemy.max_health
			enemy.max_spirit = int(enemy.max_spirit * enemy_type.spirit_mod)
			enemy.current_spirit = enemy.max_spirit
			enemy.attack = int(enemy.attack * enemy_type.attack_mod)
			enemy.defense = int(enemy.defense * enemy_type.defense_mod)
			enemy.speed = int(enemy.speed * enemy_type.speed_mod)
			enemy.ai_behavior = enemy_type.behavior
			
			# 根据等级差异调整属性
			var level_diff = enemy_level - player.level
			var level_modifier = 1.0 + (level_diff * 0.1) # 每级差异增减10%属性
			
			# 应用等级修正
			enemy.max_health = int(enemy.max_health * level_modifier)
			enemy.current_health = enemy.max_health
			enemy.attack = int(enemy.attack * level_modifier)
			enemy.defense = int(enemy.defense * level_modifier)
			
			# 设置灵石掉落范围（根据敌人等级调整）
			enemy.set_spirit_stone_drop(enemy_level, enemy_level * 3)
			
			# 开始战斗
			start_battle([enemy])
		elif rand < 0.6:
			# 30%几率发现物品
			story_text.text = "你在探索过程中发现了一些有用的物品！"
			
			# 创建随机物品
			var item = Item.new()
			item.item_name = "灵草"
			item.description = "一株普通的灵草，可以用来恢复少量生命值。"
			item.item_type = Item.ItemType.CONSUMABLE
			item.health_restore = 20
			item.max_stack = 20  # 设置最大堆叠数量
			
			# 添加到背包
			player.add_item(item)
			
			# 更新UI
			_update_game_ui()
		else:
			# 40%几率触发随机事件
			story_text.text = "你在探索过程中遇到了一位老者，他似乎有话要对你说..."
			
			# 添加对话选项
			_update_story_choices(["上前询问", "谨慎观察", "绕道而行"])


func _on_inventory_button_pressed() -> void:
	change_game_state(GameState.INVENTORY)
			# 显示战斗中的物品选择界面
			# 获取数据管理器
	var data_manager = get_node("/root/MainScene/DataManager")
			
			# 初始化装备界面（战斗模式）
	equipment_ui.initialize(player, data_manager)
			
			# 连接关闭按钮信号
	var close_button = equipment_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
	if not close_button.is_connected("pressed", _on_equipment_ui_close_pressed):
		close_button.pressed.connect(_on_equipment_ui_close_pressed)
		
	# 显示装备界面（战斗模式）
	equipment_ui.show_ui()


func _on_skills_button_pressed() -> void:
	# 显示技能界面
	change_game_state(GameState.SKILLS)
	
	# 初始化并显示技能界面
	if not skills_ui.visible:
		# 获取数据管理器
		var data_manager = get_node("/root/MainScene/DataManager")
		
		# 初始化技能界面
		skills_ui.initialize(player, data_manager)
		
		# 连接关闭按钮信号
		var close_button = skills_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
		if not close_button.is_connected("pressed", _on_skills_ui_close_pressed):
			close_button.pressed.connect(_on_skills_ui_close_pressed)
	
	# 显示技能界面
	skills_ui.show_ui()

func _on_attack_button_pressed() -> void:
	# 执行普通攻击
	if battle_system.current_state == BattleSystem.BattleState.PLAYER_TURN and battle_system.enemies.size() > 0:
		battle_system.execute_player_action("attack", -1, 0)
		
		# 更新战斗UI
		_update_battle_ui()


func _on_skill_button_pressed() -> void:
	# 显示技能选择界面
	if battle_system.current_state == BattleSystem.BattleState.PLAYER_TURN and battle_system.enemies.size() > 0:
		# 显示战斗中的技能选择界面
		if not skills_ui.visible:
			# 获取数据管理器
			var data_manager = get_node("/root/MainScene/DataManager")
			
			# 初始化技能界面（战斗模式）
			skills_ui.initialize(player, data_manager)
			skills_ui.set_battle_mode(true, battle_system)
			
			# 连接关闭按钮信号
			var close_button = skills_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
			if not close_button.is_connected("pressed", _on_battle_skills_ui_close_pressed):
				close_button.pressed.connect(_on_battle_skills_ui_close_pressed)
		
		# 显示技能界面（战斗模式）
		skills_ui.show_ui()
		
		# 暂停战斗系统（等待玩家选择技能）
		battle_system.set_paused(true)


func _on_item_button_pressed() -> void:
	# 显示物品选择界面
	if battle_system.current_state == BattleSystem.BattleState.PLAYER_TURN and battle_system.enemies.size() > 0:
		# 显示战斗中的物品选择界面
		if not equipment_ui.visible:
			# 获取数据管理器
			var data_manager = get_node("/root/MainScene/DataManager")
			
			# 初始化装备界面（战斗模式）
			equipment_ui.initialize(player, data_manager)
			equipment_ui.set_battle_mode(true, battle_system)
			
			# 连接关闭按钮信号
			var close_button = equipment_ui.get_node("MarginContainer/VBoxContainer/TitleBar/CloseButton")
			if not close_button.is_connected("pressed", _on_battle_equipment_ui_close_pressed):
				close_button.pressed.connect(_on_battle_equipment_ui_close_pressed)
		
		# 显示装备界面（战斗模式）
		equipment_ui.show_ui()
		
		# 暂停战斗系统（等待玩家选择物品）
		battle_system.set_paused(true)


func _on_flee_button_pressed() -> void:
	# 尝试逃跑
	if battle_system.current_state == BattleSystem.BattleState.PLAYER_TURN:
		battle_system.execute_player_action("flee")
		
		# 更新战斗UI
		_update_battle_ui()


func _on_story_choice_pressed(choice_index: int) -> void:
	# 处理剧情选择
	var story_text = game_ui.get_node("MainContent/StoryText")
	
	# 获取选项文本
	var choice_text = game_ui.get_node("MainContent/ChoicesContainer").get_child(choice_index).text
	
	# 检查是否在存档选择界面
	if story_text.text.begins_with("保存到存档槽位选择") or story_text.text.begins_with("读取存档槽位选择"):
		# 判断是保存还是加载操作
		var is_save = story_text.text.begins_with("保存到")
		
		# 检查是否选择了返回选项
		if choice_text == "返回":
			# 返回游戏状态
			if is_save:
				story_text.text = "你回到了主界面，可以继续你的修仙之旅。"
				_update_story_choices([])
			else:
				change_game_state(GameState.MAIN_MENU)
			return
		
		# 获取选择的存档槽位
		var slot = int(choice_text.split("号")[0]) - 1
		
		# 执行保存或加载操作
		if is_save:
			save_game(slot)
			# 返回游戏状态
			story_text.text = "你回到了主界面，可以继续你的修仙之旅。"
			_update_story_choices([])
		else:
			load_game(slot)
		return
	
	# 根据当前状态和选择处理不同的剧情分支
	if current_state == GameState.INVENTORY:
		
		# 检查是否是使用物品的选择
		if choice_text.begins_with("使用"):
			# 从选项文本中提取物品索引
			var item_index = int(choice_text.split("号")[0].split("使用")[1]) - 1
			
			# 使用物品
			if player.use_item(item_index):
				story_text.text = "你使用了物品，感觉状态好了一些。"
				
				# 更新背包显示
				_on_inventory_button_pressed()
				
				# 更新游戏UI
				_update_game_ui()
			else:
				story_text.text = "无法使用该物品。"
		else:
			# 返回主界面
			change_game_state(GameState.GAME_RUNNING)
			story_text.text = "你回到了主界面，可以继续你的修仙之旅。"
			_update_story_choices([])
	elif current_state == GameState.SKILLS:
		# 从技能界面返回
		change_game_state(GameState.GAME_RUNNING)
		story_text.text = "你回到了主界面，可以继续你的修仙之旅。"
		_update_story_choices([])
	elif story_text.text.contains("遇到了一位老者"):
		# 处理遇到老者的剧情分支
		match choice_index:
			0: # 上前询问
				var rand = randf()
				if rand < 0.4:
					# 40%几率获得修炼心得
					story_text.text = "老者微笑着看着你，从怀中取出一本古旧的竹简：\n\n'年轻人，你有缘得此修炼心得，望你好生参悟。'\n\n你获得了一些修炼经验！"
					player.gain_experience(50)
				elif rand < 0.7:
					# 30%几率获得任务
					story_text.text = "老者叹了口气：'老夫有一事相求，不知小友可愿相助？'\n\n他交给你一个特殊的任务。"
					# 触发任务系统
					story_system.emit_signal("quest_started", "old_man_quest", {"title": "老者的委托", "description": "帮助老者寻找一株千年灵芝"})
				else:
					# 30%几率遭遇陷阱
					story_text.text = "老者突然露出狰狞的笑容，原来是个妖魔伪装！你陷入了战斗！"
					# 创建一个特殊的敌人
					var enemy = Enemy.new("伪装的妖魔", player.level + 1)
					enemy.max_health *= 1.2
					enemy.attack *= 1.3
					start_battle([enemy])
			1: # 谨慎观察
				var rand = randf()
				if rand < 0.5:
					# 50%几率发现特殊物品
					story_text.text = "你仔细观察老者的举动，注意到他身边落下了一个小包裹。等他走后，你上前查看，发现是一些珍贵的丹药。"
					# 添加物品到背包
					var item = Item.new()
					item.item_name = "回春丹"
					item.description = "珍贵的丹药，可以恢复大量生命值"
					item.item_type = Item.ItemType.CONSUMABLE
					item.health_restore = 100
					item.max_stack = 10  # 设置最大堆叠数量
					player.add_item(item)
				else:
					# 50%几率发现是普通老者
					story_text.text = "经过仔细观察，你发现这只是一个普通的老者，正在休息。你选择不去打扰他。"
			2: # 绕道而行
				var rand = randf()
				if rand < 0.7:
					# 70%几率错过机缘
					story_text.text = "你选择绕道而行。走出一段距离后，回头望去，老者已经消失不见。也许你错过了一些机缘..."
				else:
					# 30%几率避开危险
					story_text.text = "你选择绕道而行。不久后，你听到原地传来一阵打斗声。看来你做出了明智的选择，避开了一场危险。\n\n你获得了一些经验！"
					player.gain_experience(30)
			
		# 如果不是战斗状态，清除选项
		if current_state != GameState.BATTLE:
			_update_story_choices([])
	else:
		# 处理主线任务选择
		if choice_text == "继续" or choice_text == "查看任务详情":
			# 获取当前主线任务
			var main_quest = story_system.get_main_quest()
			
			if not main_quest.is_empty():
				if choice_text == "查看任务详情":
					# 显示任务详情
					story_text.text = "任务: %s\n\n%s\n\n目标:" % [main_quest.title, main_quest.description]
					
					# 显示任务目标
					if main_quest.has("objectives"):
						for objective in main_quest.objectives:
							story_text.text += "\n- %s" % objective
					
					# 显示任务奖励
					if main_quest.has("rewards"):
						story_text.text += "\n\n奖励:"
						var rewards = main_quest.rewards
						
						if rewards.has("experience"):
							story_text.text += "\n- 经验: %d" % rewards.experience
						
						if rewards.has("spirit_stones"):
							story_text.text += "\n- 灵石: %d" % rewards.spirit_stones
						
						if rewards.has("items") and rewards.items.size() > 0:
							story_text.text += "\n- 物品:"
							for item in rewards.items:
								story_text.text += "\n  * %s" % item
					
					# 更新选项
					_update_story_choices(["继续任务", "返回"])
				else:
					# 继续任务
					story_text.text = "你决定继续进行任务: %s" % main_quest.title
					
					# 更新选项
					_update_story_choices(["外出寻找机缘", "静心修炼", "查看任务详情"])
			else:
				# 没有主线任务，显示默认文本
				story_text.text = "目前没有可用的主线任务。你可以自由探索世界，寻找机缘。"
				_update_story_choices(["外出寻找机缘", "静心修炼"])
		# 处理随机事件选择
		elif story_text.text.contains("随机事件:"):
			# 获取当前随机事件
			var event_title = story_text.text.split("随机事件: ")[1].split("\n")[0]
			
			# 查找匹配的随机事件
			var event_data = {}
			for event_id in story_system.story_database["random_events"]:
				var event = story_system.story_database["random_events"][event_id]
				if event.title == event_title:
					event_data = event
					event_data["id"] = event_id
					break
			
			if not event_data.is_empty():
				# 获取选择的结果
				var outcome_index = str(choice_index)
				print(event_data)
				if event_data.has("choices") and choice_index < event_data["choices"].size():
					var outcome = event_data["choices"][choice_index]
					
					# 显示结果描述
					story_text.text = outcome["outcome"]
					
					# 处理战斗
					if outcome.has("battle"):
						# 创建敌人
						var enemy = Enemy.new(outcome.battle, player.level)
						
						# 开始战斗
						start_battle([enemy])
					else:
						# 处理奖励
						if outcome.has("rewards"):
							var rewards = outcome.rewards
							
							if rewards.has("experience"):
								player.gain_experience(rewards.experience)
								story_text.text += "\n\n获得经验: %d" % rewards.experience
							
							if rewards.has("spirit_stones"):
								player.spirit_stones += rewards.spirit_stones
								story_text.text += "\n获得灵石: %d" % rewards.spirit_stones
							
							if rewards.has("karma"):
								# 处理善恶值变化
								if rewards.karma > 0:
									story_text.text += "\n你的善行被记录下来。"
								elif rewards.karma < 0:
									story_text.text += "\n你的恶行被记录下来。"
							if rewards.has("items"):
								# 处理获得的物品
								var data_manager = get_node("/root/MainScene/DataManager")
								for item_name in rewards.items:
									var item_data = data_manager.get_item_data(item_name)
									if item_data and item_data is Dictionary:
										var item = Item.new()
										item.item_name = item_data.get("name", "未知物品")
										item.description = item_data.get("description", "")
										item.item_type = item_data.get("item_type", 0)
										item.quality = item_data.get("quality", 0)
										item.value = item_data.get("value", 1)
										item.stack_size = 1
										item.max_stack = item_data.get("max_stack", 20)
										
										# 如果是装备，设置装备属性
										if item_data.has("can_equip") and item_data.can_equip:
											item.can_equip = true
											item.equip_slot = item_data.equip_slot
											item.health_bonus = item_data.get("health_bonus", 0)
											item.spirit_bonus = item_data.get("spirit_bonus", 0)
											item.attack_bonus = item_data.get("attack_bonus", 0)
											item.defense_bonus = item_data.get("defense_bonus", 0)
											item.speed_bonus = item_data.get("speed_bonus", 0)
										
										# 如果是消耗品，设置恢复属性
										if item_data.has("health_restore"):
											item.health_restore = item_data.health_restore
										if item_data.has("spirit_restore"):
											item.spirit_restore = item_data.spirit_restore
										
										player.inventory.append(item)
										print("获得物品：", item.item_name)
										story_text.text += "\n获得物品：" +item.item_name+"\n"
							
							if rewards.has("techniques"):
								# 处理获得的功法
								var data_manager = get_node("/root/MainScene/DataManager")
								for technique_name in rewards.techniques:
									var technique_data = data_manager.get_technique_data(technique_name)
									if technique_data:
										var technique = CultivationTechnique.new()
										technique.technique_name = technique_data.get("name", "未知功法")
										technique.description = technique_data.description
										technique.technique_type = technique_data.technique_type
										technique.cultivation_speed_bonus = technique_data.get("cultivation_speed_bonus", 1.0)
										technique.spirit_recovery_bonus = technique_data.get("spirit_recovery_bonus", 1.0)
										technique.breakthrough_bonus = technique_data.get("breakthrough_bonus", 1.0)
										technique.level = 1
										technique.max_level = technique_data.get("max_level", 9)
										technique.element_affinity = technique_data.get("element_affinity", "none")
										technique.required_realm = technique_data.get("required_realm", 0)
										technique.required_spirit_root = technique_data.get("required_spirit_root", "any")
										technique.attack_bonus = technique_data.get("attack_bonus", 0)
										technique.defense_bonus = technique_data.get("defense_bonus", 0)
										technique.speed_bonus = technique_data.get("speed_bonus", 0)
										
										player.cultivation_technique = technique
										print("获得功法：", technique.technique_name)
										story_text.text +="\n获得功法：" +technique.technique_name+"\n"
								
						
						# 标记事件为已完成
						story_system.completed_quests[event_data["id"]] = true
						
						# 更新选项
						_update_story_choices(["继续"])
				else:
					# 未找到对应的结果，显示默认文本
					story_text.text = "你做出了选择，但结果似乎并不明确。"
					_update_story_choices(["继续"])
			else:
				# 未找到匹配的事件，显示默认文本
				story_text.text = "你做出了选择，故事将继续发展..."
				_update_story_choices([])
		# 处理其他剧情选择
		else:
			story_text.text = "你做出了选择，故事将继续发展..."
			_update_story_choices([])

# 战斗系统回调
func _on_battle_ended(victory: bool, rewards: Dictionary) -> void:
	# 处理战斗结果
	if victory:
		# 战斗胜利
		var story_text = game_ui.get_node("MainContent/StoryText")
		story_text.text = "战斗胜利！\n\n"
		
		# 获得奖励
		if rewards.has("experience"):
			player.gain_experience(rewards.experience)
			story_text.text += "获得经验: %d\n" % rewards.experience
		
		if rewards.has("spirit_stones") and rewards.spirit_stones > 0:
			player.spirit_stones += rewards.spirit_stones
			story_text.text += "获得灵石: %d\n" % rewards.spirit_stones
		
		if rewards.has("items") and rewards.items.size() > 0:
			story_text.text += "获得物品:\n"
			for item in rewards.items:
				player.add_item(item)
				story_text.text += "- %s\n" % item.item_name
	else:
		# 战斗失败
		var story_text = game_ui.get_node("MainContent/StoryText")
		story_text.text = "战斗失败！你被打败了，但幸运的是你活了下来...\n\n你损失了一些灵石，并且受了重伤。"
		
		# 损失一些灵石
		var lost_stones = min(player.spirit_stones, player.spirit_stones / 4)
		player.spirit_stones -= lost_stones
		
		# 生命值减少
		player.current_health = max(1, player.current_health / 2)
	
	# 返回游戏状态
	change_game_state(GameState.GAME_RUNNING)

# 剧情系统回调
func _on_quest_started(quest_id, quest_data) -> void:
	# 显示任务开始信息
	var story_text = game_ui.get_node("MainContent/StoryText")
	story_text.text = "新任务: %s\n\n%s" % [quest_data.title, quest_data.description]
	
	# 添加任务选项
	_update_story_choices(["接受", "拒绝"])


func _on_quest_completed(quest_id, rewards) -> void:
	# 显示任务完成信息
	var story_text = game_ui.get_node("MainContent/StoryText")
	story_text.text = "任务完成！\n\n"
	
	# 获得奖励
	if rewards.has("experience"):
		player.gain_experience(rewards.experience)
		story_text.text += "获得经验: %d\n" % rewards.experience
	
	if rewards.has("spirit_stones") and rewards.spirit_stones > 0:
		player.spirit_stones += rewards.spirit_stones
		story_text.text

func _on_random_event_triggered(event_id, event_data) -> void:
	# 显示随机事件信息
	var story_text = game_ui.get_node("MainContent/StoryText")
	story_text.text = "随机事件: %s\n\n%s" % [event_data.title, event_data.description]
	
	# 添加事件选项
	_update_story_choices(event_data.choices)

func _on_dialogue_started(dialogue_data) -> void:
	# 切换到对话状态
	change_game_state(GameState.DIALOGUE)
	
	# 显示对话内容
	var story_text = game_ui.get_node("MainContent/StoryText")
	story_text.text = dialogue_data.content
	
	# 添加对话选项
	_update_story_choices(dialogue_data.choices)


# 初始化剧情
func _initialize_story() -> void:
	# 重置剧情进度
	story_system.current_chapter = 0
	story_system.current_quest = 0
	story_system.completed_quests.clear()
	
	# 切换到游戏状态
	change_game_state(GameState.GAME_RUNNING)
	
	# 获取主线任务
	var main_quest = story_system.get_main_quest()
	
	# 显示初始剧情
	var story_text = game_ui.get_node("MainContent/StoryText")
	
	if not main_quest.is_empty():
		# 显示主线任务信息
		story_text.text = "主线任务: %s\n\n%s" % [main_quest.title, main_quest.description]
		
		# 如果有对话数据，显示对话
		if main_quest.has("dialogues") and main_quest["dialogues"].has("start"):
			var dialogue = main_quest["dialogues"]["start"]
			story_text.text += "\n\n%s: %s" % [dialogue.npc, dialogue.content]
			
			# 添加对话选项
			_update_story_choices(dialogue.choices)
		else:
			# 添加默认选项
			_update_story_choices(["继续", "查看任务详情"])
	else:
		# 显示默认初始剧情
		story_text.text = "你是一个刚刚踏入修仙之路的凡人，前方等待着你的是无尽的机遇与挑战。\n\n你的灵根资质平平，但这并不妨碍你对长生大道的向往。现在，你需要做出选择，是外出寻找机缘，还是先静心修炼提升自己？"
		
		# 添加初始选项
		_update_story_choices(["外出寻找机缘", "静心修炼", "了解更多信息"])
	
	# 发出章节变化信号
	story_system.emit_signal("chapter_changed", story_system.current_chapter)

# 处理角色创建取消的回调
func _on_character_creation_cancelled() -> void:
	# 返回主菜单状态
	change_game_state(GameState.MAIN_MENU)
	
	# 显示初始剧情
	var story_text = game_ui.get_node("MainContent/StoryText")
	story_text.text = "你是一个刚刚踏入修仙之路的凡人，前方等待着你的是无尽的机遇与挑战。\n\n你的灵根资质平平，但这并不妨碍你对长生大道的向往。现在，你需要做出选择，是外出寻找机缘，还是先静心修炼提升自己？"
	
	# 添加初始选项
	_update_story_choices(["外出寻找机缘", "静心修炼", "了解更多信息"])
	
	# 发出章节变化信号
	story_system.emit_signal("chapter_changed", story_system.current_chapter)
